package com.glorysoft.tonglingxjpda.ui.function.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.icu.text.SymbolTable
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.glorysoft.tonglingxjpda.R
import com.glorysoft.tonglingxjpda.base.Constant
import com.glorysoft.tonglingxjpda.base.DataBindBaseViewHolder
import com.glorysoft.tonglingxjpda.bindingadapter.PopOneChooseAdapter
import com.glorysoft.tonglingxjpda.databinding.ItemKyhBinding
import com.glorysoft.tonglingxjpda.databinding.ItemKyhDlBinding
import com.glorysoft.tonglingxjpda.entity.KyhEntity
import com.glorysoft.tonglingxjpda.entity.net.HeaderBean
import com.glorysoft.tonglingxjpda.entity.net.NetRequestBean
import com.glorysoft.tonglingxjpda.entity.net.ReturnBean
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.utils.PopWindowsUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_SimpleDialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils
import org.apache.commons.lang3.StringEscapeUtils
import java.lang.reflect.Field
import java.lang.reflect.Method
import java.util.*
import kotlin.collections.ArrayList


/**
 * FileName: KyhAdapter
 * Author: XJH
 * Date: 2021/8/10 11:39
 * Description:
 * History:
 */
class KyhAdapter(data: List<KyhEntity.ComponentEntity>, val po: String, val name: String,val reserved : String) :
    BaseQuickAdapter<KyhEntity.ComponentEntity, DataBindBaseViewHolder>(
//        R.layout.item_kyh, data
        R.layout.item_kyh_dl, data
    ) {
//    private val handler = Handler()
//    private var delayRun: Runnable? = null
//    private var flag: Boolean = true
    var hintList : ArrayList<String> = arrayListOf()

    override fun convert(helper: DataBindBaseViewHolder, item: KyhEntity.ComponentEntity) {
//        helper.setIsRecyclable(false)
//        val itemKyhBinding = helper.getDataBinding() as ItemKyhBinding
        val itemKyhBinding = helper.getDataBinding() as ItemKyhDlBinding
        itemKyhBinding.partItem = item
        val mAdapter =
            ArrayAdapter(mContext, android.R.layout.simple_list_item_1, hintList)
        val etSn: AutoCompleteTextView = helper.getView(R.id.etSn)
        etSn.isEnabled = reserved == "Spilt"
        etSn.setAdapter(mAdapter)
//        setEditListener(etSn,mAdapter)
        val llPartLayout: LinearLayout = helper.getView(R.id.llPartLayout)
        llPartLayout.setOnClickListener{
            if (reserved != "Spilt"){
                FreeApi_ToastUtils.showFreeToast("当前刻印号不允许输入",mContext,false,0)
            }
        }

    }

    private fun setEditListener(editText: AutoCompleteTextView,adapter: ArrayAdapter<String>) {
        if (editText.tag is TextWatcher) {
            editText.removeTextChangedListener(editText.tag as TextWatcher)
        }
        val watcher: TextWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

                if (reserved != "Spilt"){
                    FreeApi_ToastUtils.showFreeToast("当前刻印号不允许输入",mContext,false,0)
                    editText.setText("")
                    return
                }
//                if (editText.text.toString().isEmpty()){
//                    adapter.clear()
//                    return
//                }

                /**延迟线程，看是否还有下一个字符输入*/
//                if (delayRun != null) {
//                    //每次editText有变化的时候，则移除上次发出的延迟线程
//                    handler.removeCallbacks(delayRun)
//                }
//                delayRun = Runnable { getHint(s.toString(), adapter,editText) }
//                if (s.toString().length >= 4 && adapter.count <= 0) {
//                    //延迟500ms，如果不再输入字符，则执行该线程的run方法
//                    handler.postDelayed(delayRun, 500)
//                }

            }

            override fun afterTextChanged(s: Editable) {
            }
        }
        editText.addTextChangedListener(watcher)
        editText.tag = watcher
    }

    fun getHint(adapter: ArrayAdapter<String>) {
        val json = JsonObject()
        json.addProperty("ACTIONTYPE", "COMPONENTUMIT")
        json.addProperty("DOCID", po)
        json.addProperty("PARTNAME", name)
//        json.addProperty("COMPONENTALIAS", hint)
        var callBack = object :
            FreeUI_SimpleDialogEntityCallBack<ReturnBean<KyhEntity>>(mContext as AppCompatActivity) {

            override fun onSuccess(response: Response<ReturnBean<KyhEntity>>) {
                super.onSuccess(response)
                if (response.body().header.result == "SUCCESS") {
                    val data = response.body().body
                    adapter.clear()
                    if (data.COMPONENTUNIT.isNotEmpty()) {
                        data.COMPONENTUNIT.forEach {
                            adapter.add(it.COMPONENTALIAS)
                        }
                    }
                }

            }

            override fun onError(response: Response<ReturnBean<KyhEntity>>) {
                super.onError(response)

            }

        }

        val format: NetRequestBean<*> = NetRequestBean<Any?>()
        format.body = json
        format.header = HeaderBean("TL.TLCOMPONENTUMIT")
        val map: MutableMap<String, String> = HashMap()
        map["senderId"] = "EAP2MESSender"
        map["requestMessage"] = StringEscapeUtils.unescapeJson(Gson().toJson(format))
        Log.e("请求JSON", "getInJsonData: " + StringEscapeUtils.unescapeJson(Gson().toJson(format)))
        OkGo.post<ReturnBean<KyhEntity>>(Constant.REQUEST_URL_DEBUG + "/esbrest/RestService/postrequest")
            .tag(mContext)
            .params(map, true)
            .execute(callBack)
    }

//    fun updateDataToAutoComplete(adapter: SearchHintAdapter,newData : List<String>) {
//        try {
//            val simpleAdapterClass = Class.forName("android.widget.SimpleAdapter")
//            val searchList: Field = simpleAdapterClass.getDeclaredField("mUnfilteredData")
//            searchList.isAccessible = true
//            searchList.set(adapter, newData)
//        } catch (e: ClassNotFoundException) {
//            e.printStackTrace()
//            Log.e(TAG, "updateDataToAutoComplete:exception=" + e.message)
//        } catch (e: NoSuchFieldException) {
//            e.printStackTrace()
//            Log.e(TAG, "updateDataToAutoComplete:exception=" + e.message)
//        } catch (e: IllegalAccessException) {
//            e.printStackTrace()
//            Log.e(TAG, "updateDataToAutoComplete:exception=" + e.message)
//        }
//    }

//    @SuppressLint("SoonBlockedPrivateApi")
//    fun refreshDropList(autoTv : AutoCompleteTextView){
//        try {
//            val autoCompleteTextView = Class.forName("android.widget.AutoCompleteTextView")
//            val doBeforeTextChanged : Method = autoCompleteTextView.getDeclaredMethod("doBeforeTextChanged")
//            doBeforeTextChanged.isAccessible = true
//            val doAfterTextChanged : Method = autoCompleteTextView.getDeclaredMethod("doAfterTextChanged")
//            doAfterTextChanged.isAccessible = true
//            autoTv.showDropDown()
//            doBeforeTextChanged.invoke(autoTv)
//            doAfterTextChanged.invoke(autoTv)
//        }catch (e : Exception){
//            Log.e(TAG, "refreshDropList: 反射调用失败")
//        }
//
//    }

    fun getOneChoosePop(
        context: Context, width: Int, list: List<String>,
        textAndPositionCallback: PopWindowsUtils.PopTextAndPositionCallback
    ): PopWindowsUtils.GeneralPop {
        val mView: View = LayoutInflater.from(context)
            .inflate(R.layout.pop_string_list, null)
        val recyclerView: RecyclerView =
            mView.findViewById(R.id.rvList)
        recyclerView.layoutManager = LinearLayoutManager(context)
        val generalPop = PopWindowsUtils.GeneralPop(
            context, mView, width, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        val popListAdapter = PopOneChooseAdapter(list)
        popListAdapter.setOnItemClickListener { adapter, _, position ->
            textAndPositionCallback.onSuccess(
                java.lang.String.valueOf(adapter.getItem(position)),
                position
            )
            generalPop.dismiss()
        }
        recyclerView.adapter = popListAdapter
        generalPop.isOutsideTouchable = true
        return generalPop
    }

}